package com.zme.controller;

import com.zme.util.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
public class springmvcController {
//    private String BASE_PATH = ""
    @RequestMapping("/welcome")
    public String welcome(String username){
        System.out.println(username);
        return "success";
    }

    @RequestMapping(value = "ajaxDemo",produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String ajaxDemo(String username){
        System.out.println(username);
        return username;
    }

    @RequestMapping(value = "ajaxUpload",produces = {"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    public ResponseResult ajaxUplod(ResponseResult responseResult, MultipartFile file, HttpServletRequest request){
        // 获取上传文件的原始名称
        String fileName = file.getOriginalFilename();
        // 获取上传文件的后缀名
        String ext = fileName.substring(fileName.lastIndexOf("."));
        // 获取当前项目资源文件的绝对路径
        StringBuilder stringBuilder1 = new StringBuilder(request.getSession().getServletContext().getRealPath("/"));
        String baseUrl = stringBuilder1.toString();
        // 设置本地文件的相对路径
        StringBuilder stringBuilder2 = new StringBuilder(File.separator);
        stringBuilder2.append("upload");
        stringBuilder2.append(File.separator);
        stringBuilder2.append(Calendar.YEAR);
        stringBuilder2.append("-");
        stringBuilder2.append(Calendar.MONTH);
        stringBuilder2.append("-");
        stringBuilder2.append(Calendar.DATE);
        stringBuilder2.append(ext);
        String fileUrl = stringBuilder2.toString();
        // 当前项目路径 + 文件存储的相对路径 = 上传文件存储的绝对路径
        File localFile = new File(stringBuilder1.append(stringBuilder2).toString());
        Map<String,Object> map = new HashMap();
        // 将文件的相对路径返回给前端实现文件预览
        map.put("fileUrl",fileUrl);
        if(!localFile.exists()){
            localFile.mkdirs();
        }
        try {
            file.transferTo(localFile);
            responseResult.setDataState("success");
            responseResult.setMsg("上传成功");
            responseResult.setResponseMap(map);
        } catch (IOException e) {
            responseResult.setDataState("fail");
            responseResult.setMsg("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }
}
